<template>
  <div class="home_wrap">
    <van-pull-refresh
      v-model="isLoading"
      :disabled="disabledFresh"
      @refresh="onRefresh"
      success-text="刷新成功"
    >
      <div class="home" @scroll="scrollHeight" v-if="showPage">
        <!-- 广告图 -->
        <div class="swiper">
          <van-swipe class="my-swipe" :autoplay="3000" indicator-color="white">
            <van-swipe-item>
              <img src="../assets/banner.jpg" alt="" />
            </van-swipe-item>
          </van-swipe>
        </div>
        <!-- 本周课程列表 -->
        <div class="assets_list">
          <div class="title-wrapper">
            <div class="title">近期课程</div>
            <div class="more-link" v-if="thisWeekCourse.length > 2" @click="goToCourseMore">
              查看更多
            </div>
          </div>
          <div class="records" v-if="recentCourses.length">
            <div class="item"
              v-for="(item, index) in recentCourses"
              :key="index"
              @click="clickDetail(item)"
            >
              <div class="records_item_title">{{item.className}}（{{item.studentName}}）</div>
              <div class="records_item_remarks" v-if="item.remarks">{{item.remarks}}</div>
              <div class="records_item_detail">
                <div class="qixian">
                  <div class="detail_title">上课开始时间:</div>
                  <div class="num mainColor">{{item.startTime}}</div>
                </div>
              </div>
            </div>
          </div>
          <div class="no-data" v-else>
            暂无数据
          </div>
        </div>
        <!-- 其他课程列表 -->
        <div class="assets_list" style="margin-top: 20px;" v-if="allCourse.length">
          <div class="title">课程列表</div>
          <div class="records">
            <div class="item_all_list"
              v-for="(item, index) in allCourse"
              :key="index"
              @click="clickDetailCourse(item.id)"
            >
              <div class="item_wrap">
                <div class="item_wrap_img">
                  <img :src="`${item.image}`" alt="" style="width:100%;height:100%;" />
                </div>
                <div class="item_wrap_detail">
                  <div class="item_wrap_title">{{ item.className }}</div>
                  <div class="price mainColor">现价：{{ item.price }}</div>
                  <div class="detail_title" v-if="item.remarks && item.remarks.length">{{item.remarks}}</div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </van-pull-refresh>
  </div>
</template>

<script>
import { Swipe, SwipeItem, PullRefresh, Toast } from 'vant'
export default {
  name: 'Home',
  components: {
    [Swipe.name]: Swipe,
    [SwipeItem.name]: SwipeItem,
    [PullRefresh.name]: PullRefresh
  },
  data() {
    return {
      showPage: false,
      disabledFresh: false, // 禁用下啦刷新
      isLoading: false,
      thisWeekCourse: [], // 本周课程列表
      allCourse: [], // 所有课程列表
    }
  },
  computed: {
    recentCourses() {
      // 只显示最近的2条记录
      return this.thisWeekCourse.slice(0, 2)
    }
  },
  /**
   * px_token   fpjS0Jk1RKALgJcSpyWUkaWtaDDWVwsx5Ihp1+3Yhsc=
   * px_user_openid    odeJO56ykTcy1rd2HirlWziW-l3c
   *
   * http://192.168.2.100:8080/
   *
   */
  beforeRouteEnter(to, from ,next) {
    console.log('beforeRouteEnter', from)
    next(async vm => {
       // if (!window.localStorage.getItem('px_token')) {
       // window.localStorage.setItem('px_token', 'fpjS0Jk1RKALgJcSpyWUkaWtaDDWVwsx5Ihp1+3Yhsc=')
       // window.localStorage.setItem('px_user_openid', 'odeJO56ykTcy1rd2HirlWziW-l3c')
       if (from.path == '/' || from.path == '/home' || from.path == '/login') {
        try {
          let code = vm.getCode(to.path);
          if (!code) return
          let ret = await vm.$http.getUserIfRegister({code})
          vm.handleToken(ret, vm, to.path)
        } catch(err) {
          let code = vm.redirectGetCode(to.path);
          let ret = await vm.$http.getUserIfRegister({code})
          vm.handleToken(ret, vm, to.path)
        }
      } else {
        vm.getData()
      }
    })
  },
  methods: {
    handleToken(ret, that, path) {
      localStorage.setItem('px_user_openid', ret.data.result.openId)
      if (!ret.data.result.token) {
        that.$router.push({name: 'login', params: {prevName: path }})
      } else {
        localStorage.setItem('px_token', ret.data.result.token)
        // 保存完整的登录数据到缓存
        that.$store.dispatch('saveLoginData', ret.data)
      }
      that.getData()
    },
    getData() {
      this.$http.getCourseWeekList().then(res => {
        this.isLoading = false
        this.showPage = true;
        this.thisWeekCourse = res.data.result
      }).catch(err => {
        this.isLoading = false
        this.showPage = true;
        console.log(err, 'err')
        this.$toast(err.data.message)
      })
      this.$http.getAllCourselist().then(res => {
        this.allCourse = res.data.result
        this.showPage = true;
      }).catch(err => {
        this.isLoading = false
        this.showPage = true;
        console.log(err, 'err')
        this.$toast(err.data.message)
      })
    },
    onRefresh() {
      this.getData()
    },
    clickDetail(item) {
      this.$router.push({
        name: 'class-detail',
        params: {
          classId: item.classId,
          courseScheduleId: item.courseScheduleId,
          id: item.id,
          studentId: item.studentId,
          startTime: item.startTime,
          endTime: item.endTime,
          from: 'home'
        }
      })
    },
    clickDetailCourse(e) {
      this.$router.push({ name: 'common-product-detail', params: { id: e, from: 'home' } })
    },
    scrollHeight(e) {
      if (e.srcElement.scrollTop === 0) {
        this.disabledFresh = false
      } else {
        this.disabledFresh = true
      }
    },
    goToCourseMore() {
      this.$router.push({ name: 'course-more' })
    }
  }
}
</script>

<style lang="scss" scoped>
  .home_wrap {
    color: #333;
    width: 100%;
    height: 100%;
    overflow: scroll;
    overflow-x: hidden;
    .home {
      width: 100%;
      height: 100%;
      overflow: scroll;
      background: #fff;
      .swiper {
        width: 100%;
        height: 200px;
      }
      .assets_list {
        width: 100%;
        padding: 0px 20px;
        box-sizing: border-box;
        .title-wrapper {
          display: flex;
          align-items: center;
          justify-content: space-between;
          padding: 10px 0px;
          box-sizing: border-box;
        }
        .title {
          font-size: 18px;
          text-align: left;
          font-weight: 600;
        }
        .over {
          font-size: 12px;
          color: #8E8E93 !important;
          text-align: left;
          padding: 10px 0px 0px;
          box-sizing: border-box;
        }
        .item {
          min-height: 100px;
          position: relative;
          margin-top: 10px;
          padding: 18px 20px;
          background: #fff;
          box-sizing: border-box;
          box-shadow: 0 4px 15px 0 rgba(0,0,0,0.09);
          border-radius: 4px;
          display: flex;
          flex-direction: column;
          .records_item_title {
            width: 100%;
            min-height: 25px;
            font-weight: 900;
            text-align: left;
            color: #333;
          }
          .records_item_remarks {
            width: 100%;
            color: #999;
            margin-top: 5px;
            font-size: 14px;
            white-space: nowrap;
            text-overflow: ellipsis;
            overflow: hidden;
          }
          .records_item_detail {
            margin-top: 10px;
            flex: 1;
            display: flex;
            align-items: center;
            justify-content: space-between;
            .qixian {
              width: 100%;
              display: flex;
              align-items: center;
              justify-content: space-between;
            }
            .num {
              font-size: 14px;
              font-weight: bolder;
            }
            .detail_title {
              font-size: 14px;
              color: #999;
            }
          }
        }
        .item_all_list {
          position: relative;
          margin-top: 10px;
          padding: 14px 16px;
          background: #fff;
          box-sizing: border-box;
          box-shadow: 0 4px 15px 0 rgba(0, 0, 0, 0.09);
          border-radius: 4px;
          display: flex;
          flex-direction: column;
          .item_wrap {
            display: flex;
            align-items: center;
            .item_wrap_img {
              width: 70px;
              height: 70px;
            }
            .item_wrap_detail {
              flex: 1;
              overflow: hidden;
              display: flex;
              flex-direction: column;
              justify-content: space-between;
              height: 100%;
              padding: 0px 10px;
              box-sizing: border-box;
              .item_wrap_title {
                width: 100%;
                min-height: 25px;
                font-weight: 900;
                text-align: left;
                color: #333;
              }
              .price {
                font-size: 14px;
              }
              .detail_title {
                width: 100%;
                font-size: 14px;
                color: #999;
                overflow:hidden;
                text-overflow:ellipsis;
                display:-webkit-box;
                -webkit-box-orient:vertical;
                -webkit-line-clamp:2;
              }
            }
          }
        }
        .no-data {
          text-align: center;
          color: #999;
          font-size: 14px;
          padding: 20px 0;
        }
        .more-link {
          color: #007bff;
          font-size: 14px;
          cursor: pointer;
        }
        .more-link:hover {
          color: #0056b3;
        }
      }
      .bottom {
        font-size: 12px;
        color: #999;
        display: flex;
        margin-top: 30px;
        margin-bottom: 20px;
        align-items: center;
        justify-content: center;
        .mine_bot {
          width: 294px;
          height: 39px;
        }
      }
    }

  }
</style>
<style lang="scss">
  .home_wrap {
    .my-swipe {
      height: 100%;
      .van-swipe-item {
        width: 100%;
        height: 100%;
      }
    }
    .van-pull-refresh {
      height: 100%;
    }
  }
</style>
